import {
  Component,
  OnInit,
  ElementRef 
} from '@angular/core';

import { DomSanitizer } from '@angular/platform-browser';

import { AppState } from '../app.service';
import { Title } from './title';
import { XLargeDirective } from './x-large';

class MyStore {
  remove(key: any): any {
    let savekey = this.prefix + JSON.stringify(key);
    this.cacheMap.delete(savekey);
    window.localStorage.removeItem(savekey);
  }
  prefix: string;
  cacheMap: Map<any, any>;
  constructor(prefix = "mystore__") {
    this.cacheMap = new Map();
    this.prefix = prefix;
  }
  save(key: string, value) {
    let savekey = this.prefix + JSON.stringify(key);
    this.cacheMap.set(savekey, value);
    window.localStorage.setItem(savekey, JSON.stringify(value));
  }
  get(key) {
    let savekey = this.prefix + JSON.stringify(key);
    let storevalue = window.localStorage.getItem(savekey);
    if (storevalue) {
      this.cacheMap.set(savekey, storevalue);
    }
  }
  getAll() {
    let self = this;
    let arr = [];
    for (let i = 0; i < localStorage.length; i++) {
      let key = localStorage.key(i);
      if (key.indexOf(self.prefix) > -1) {
        arr.push(JSON.parse(localStorage.getItem(key)));
      }
    }
    return arr;
  }
}


let myStore = new MyStore();


@Component({
  /**
   * The selector is what angular internally uses
   * for `document.querySelectorAll(selector)` in our index.html
   * where, in this case, selector is the string 'home'.
   */
  selector: 'home',  // <home></home>
  /**
   * We need to tell Angular's Dependency Injection which providers are in our app.
   */
  providers: [
    Title
  ],
  /**
   * Our list of styles in our component. We may add more to compose many styles together.
   */
  styleUrls: [ './home.component.css' ],
  /**
   * Every Angular template is first compiled by the browser before Angular runs it's compiler.
   */
  templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
  /**
   * Set our default values
   */
  public localState = { value: '' };
  /**
   * TypeScript public modifiers
   */
  constructor(
    public appState: AppState,
    public title: Title,
    private elementRef: ElementRef,
    private sanitizer: DomSanitizer
  ) {
  }

  public ngOnInit() {
    let self = this;
    /**
     * this.title.getData().subscribe(data => this.data = data);
     */
    let iframe = this.elementRef.nativeElement.querySelector('#iframe');
    iframe.onload = function() {
      // console.log(this.contentWindow.document.querySelector("#translateio"));
    }

    this.updateWords();
    if (this.words && this.words.length > 0) {
      this.lookTranslate(self.words[0].value);
    }
  }

  updateWords() {
    this.words = myStore.getAll().sort((a, b) => {
      return a.created - b.created;
    });
  }

  public submitState(value: string) {
    console.log('submitState', value);
    this.appState.set('value', value);
    this.localState.value = '';
  }

  public newword = "";
  public words = [];

  public onAddWord() {
    // console.log("add new word");
    let self = this;
    myStore.save(self.newword, {
      value: self.newword,
      created: Date.now(),
      updated: Date.now()
    });
    self.newword = "";
    this.updateWords();
  }

  transform(url) {
    return this.sanitizer.bypassSecurityTrustResourceUrl(url);
  }

  public translateUrl;
  public lookTranslate(value) {
    this.translateUrl = this.transform(`http://fanyi.baidu.com/#zh/jp/${encodeURIComponent(value)}`);
  }

  public deleteWord(key) {
    let self = this;
    myStore.remove(key);
    this.updateWords();
  }
}
